package com.caiheng.api.aop;

import cn.hutool.core.util.StrUtil;
import com.caiheng.api.commons.config.SqlFilterArgumentResolver;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.DateUtil;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Optional;
import java.util.function.Function;

@Configuration
public class TokenConfigurer implements WebMvcConfigurer {

	@Autowired
	private UserService userService;

	@Value("${web.isOpenValidate}")
	private Integer isOpenValidate;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new HandlerInterceptor() {
			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//				System.out.println("======isOpenValidate========="+ isOpenValidate);
				String accessToken = request.getHeader("access_token");
				String userId = request.getHeader("user_id");
				String address = request.getRemoteAddr();
				if(isOpenValidate == 1){
					if (StrUtil.isEmpty(accessToken)) {
						response.setCharacterEncoding("utf-8");
						response.setContentType("application/json; charset=utf-8");
						PrintWriter writer = response.getWriter();
						writer.write(Tools.getJson(new GsonResultBean<>(2, "非法访问，请先登录！"), true, true).toString());
						System.out.println("非法访问： accessToken： " + accessToken + ", " + DateUtil.getTime() + "------ 请求的IP地址： " + address);
						return false;
					}
					if (StrUtil.isEmpty(userId)) {
						response.setCharacterEncoding("utf-8");
						response.setContentType("application/json; charset=utf-8");
						PrintWriter writer = response.getWriter();
						writer.write(Tools.getJson(new GsonResultBean<>(2, "非法访问，userId为空！"), true, true).toString());
						System.out.println("非法访问： userId： " + userId + ", " + DateUtil.getTime()+ "------ 请求的IP地址： " + address);
						return false;
					}

					if(StrUtil.isNotEmpty(userId) && userId.equals("817")){
						response.setCharacterEncoding("utf-8");
						response.setContentType("application/json; charset=utf-8");
						PrintWriter writer = response.getWriter();
						writer.write(Tools.getJson(new GsonResultBean<>(2, "非法访问，请先登录！"), true, true).toString());
						System.out.println("非法访问： accessToken： " + accessToken + ", " + DateUtil.getTime() + "------ 请求的IP地址： " + address);
						return false;
					}

					Boolean access = Optional.ofNullable(userService.getById(userId))
							.map((Function<User, Object>) User::getToken)
							.map(t -> t.equals(accessToken)).orElse(false);
					if (!access) {
						response.setCharacterEncoding("utf-8");
						response.setContentType("application/json; charset=utf-8");
						PrintWriter writer = response.getWriter();
						writer.write(Tools.getJson(new GsonResultBean<>(2, "非法访问，请先登录！"), true, true).toString());
						System.out.println("非法访问： access： " + access.booleanValue() + ", " + DateUtil.getTime()+ "------ 请求的IP地址： " + address);
					}
					return access;
				}else{
					if(StrUtil.isNotEmpty(userId) && userId.equals("817")){
						response.setCharacterEncoding("utf-8");
						response.setContentType("application/json; charset=utf-8");
						PrintWriter writer = response.getWriter();
						writer.write(Tools.getJson(new GsonResultBean<>(2, "非法访问！"), true, true).toString());
						System.out.println("非法访问： accessToken： " + accessToken + ", " + DateUtil.getTime() + "------ 请求的IP地址： " + address);
						return false;
					}
//					System.out.println("请求的IP地址： " + address);
					return  true;
				}
			}

			@Override
			public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

			}

			@Override
			public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

			}
		}).addPathPatterns("/**").excludePathPatterns("/user/wxLogin").excludePathPatterns("/product/type/list")
				.excludePathPatterns("/device/material/list").excludePathPatterns("/product/detail").excludePathPatterns("/farm/info")
				.excludePathPatterns("/device/detail").excludePathPatterns("/device/init").excludePathPatterns("/device/appVersion")
				.excludePathPatterns("/index/index").excludePathPatterns("/user/getUserInfoById");

	}

//	/**
//	 * SQL 过滤器避免SQL 注入
//	 * @param argumentResolvers
//	 */
//	@Override
//	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
//		argumentResolvers.add(new SqlFilterArgumentResolver());
//	}
}
